<template>
  <div class="global-field">
    <page-box>
      <template #top>
        <alert-msg
          content="【客户信息】主要用于控制【客户池】、【客户详情】等客户模块可以应用哪些字段，如需要设置【客户信息】，需要先在【自定义字段】进行配置后再添加进【客户信息】"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="getData"></search-form>
      </template>
      <template #btn>
        <el-button @click="getData">查询</el-button>
        <el-button @click="addInfoFun({}, 'add')" type="primary"> 新建 </el-button>
      </template>
      <template #table>
        <resize-table :headers="tableHeaders" :data="tableData" :showPagination="false" rowKey="name">
          <!-- 拖拽 -->
          <template #drag>
            <i class="MC_iconfont MC_icon-tuodong-shu1 drag"></i>
          </template>
          <!-- 类型 -->
          <template #type="{ scope }">
            <span>{{ typeAllMap[scope.row.type] }}</span>
          </template>
          <!-- 操作 -->
          <template #oprate="{ scope }">
            <!-- 预置的不展示移除 -->
            <span v-if="scope.row.glFieldId" class="btn" @click="addInfoFun(scope.row, 'edit')">编辑</span>
            <span
              v-if="scope.row.glFieldId && !['customerName', 'mobile'].includes(scope.row.field)"
              class="btn"
              @click="moveField(scope.row)"
              >移除</span
            >
          </template>
        </resize-table>
      </template>
    </page-box>
    <add-info ref="addCusInfo" @onUpdateList="getData"></add-info>
  </div>
</template>

<script lang="ts" setup>
import { computed, getCurrentInstance, onMounted, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import searchForm from '@/common/components/base-form/form.vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import alertMsg from '@common/components/alert/index.vue'
import addInfo from './add-info.vue'
import pageBox from '@common/components/page-box.vue'
import Sortable from 'sortablejs'
import { infoList, removeField, sortField } from '@app/customer/apis/info'
import { typeArr, typeAllMap } from '@app/base/views/account/components/global-field/type'
import mcCache from '@/common/utils/mc-get-cache'
import { commonStore } from '@/common/store/modules/common'
interface State {
  fieldList: Record<string, unknown>[]
  form: Record<string, unknown>
  tableHeaders: Record<string, unknown>[]
  tableData: Record<string, unknown>[]
  allDataObj: any
}

const instance: any = getCurrentInstance()

const state: State = reactive({
  fieldList: [
    {
      name: '字段名称',
      field: 'name',
      type: 'text'
    },
    {
      name: '字段类型',
      field: 'type',
      type: 'dropdown',
      multiple: true,
      choices: typeArr('all')
    }
  ],
  form: {
    type: []
  },
  tableHeaders: [
    {
      label: '',
      prop: 'drag',
      width: 60,
      show: true,
      custom: true
    },
    { label: '字段名称', prop: 'name', show: true },
    { label: '字段类型', prop: 'type', show: true, custom: true },
    { label: '字段参数', prop: 'param', show: true },
    { label: '操作', prop: 'oprate', show: true }
  ],
  tableData: [],
  allDataObj: {} // 全部列表的以field为key的全局字段
})

// 移除
const moveField = (row: any) => {
  ElMessageBox.confirm('移除字段后【客户池】等模块均不可使用该字段，请确认是否移除？', '移除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removeField({
      field: row.field
    }).then((res) => {
      if (res.success) {
        ElMessage.success('操作成功')
        getData()
        // 更新pinia
        mcCache.$deleteCache('cusInfo', 'field', row.field, '')
      }
    })
  })
}

// 新建字段
const addInfoFun = async (row: any, type: string) => {
  // 全局字段
  await mcCache.$getCache('globalFieldCache', 'hasObj', '', '', '', '', 'field') // 全局字段
  await getAlData()
  instance?.refs.addCusInfo.openDialog(state.allDataObj, row, type)
}

const cusInfo = computed(() => {
  return commonStore().publicCache.cusInfo || []
})

// 全部客户信息字段中的 全局字段 {field: {}}
const getAlData = async () => {
  state.allDataObj = {} // 清空数据
  await mcCache.$getCache('cusInfo', 'hasObj', '', '', '', '', 'field')
  if (cusInfo.value && cusInfo.value.length) {
    cusInfo.value.forEach((item: any) => {
      if (item.glFieldId) {
        state.allDataObj[item.field] = item
      }
    })
  }
}

// 获取字段
const getData = () => {
  infoList(state.form).then((res: any) => {
    if (res.success && res.data) {
      state.tableData = res.data || []
    }
  })
}

// 行拖拽
const rowDrop = () => {
  const body = document.querySelector('.el-table__body-wrapper tbody')
  Sortable.create(body, {
    animation: 1000,
    handle: '.drag',
    onEnd({ newIndex, oldIndex }: any) {
      const currRow = state.tableData.splice(oldIndex, 1)[0]
      state.tableData.splice(newIndex, 0, currRow)
      const sendData = {
        filed: state.tableData[newIndex].field,
        targetId: newIndex > oldIndex ? state.tableData[newIndex - 1].field : state.tableData[newIndex + 1].field
      }
      sortField(sendData).then((res) => {
        if (res.success) {
          ElMessage.success('操作成功')
        }
      })
    }
  })
}

onMounted(() => {
  /* 清空pinia中的数据 重新获取数据存储 保证存储的数据为最新的 eg: 添加到表格中的全局字段停用，获取数据从表格中移除 需更新缓存 */
  commonStore().publicCache.cusInfo = []
  getData()
  rowDrop()
})

const { fieldList, form, tableHeaders, tableData } = toRefs(state)
</script>

<style lang="stylus">
.global-field {
  .MC_icon-xinxi-mian {
    color: var(--mc-link-color);
    margin-right: 10px;
  }

  .drag {
    color: rgba(0, 0, 0, 0.38);
    cursor: move;
  }

  .btn {
    color: var(--mc-main-color);
    cursor: pointer;
    margin-right: 16px;

    &:last-child {
      margin-right: 0px;
    }
  }
}
</style>
